/**
 * project: finance-manage
 * package: com.example.dataAccess
 * 数据库操作基类
 */

package com.example.dataAccess;

/* 引入 */
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/* 抽象类 */
public abstract class DAO_Base {
    /* 数据库连接器 */
    protected Connection connection;

    /* sql语句执行器 */
    protected PreparedStatement pstatement;

    /* 构造方法? 当传入数据库连接器时 */
    public DAO_Base(Connection connection) {
        /* 设置数据库连接器 */
        this.connection = connection;
    }

    /* 构造方法? 当不传入数据库连接器时 */
    public DAO_Base() throws IOException, SQLException {
        /* 获取一个连接器 */
        try {
            Connect connect = new Connect();
            this.connection = connect.getConnection();
        } catch (IOException e) {
            /* 便于拓展 */
            throw new IOException(e);
        } catch (SQLException e) {
            /* 便于拓展 */
            throw new SQLException(e);
        }
    }

    /* 执行SQL语句 */
    protected boolean executeUpdate(String sql, Object... args) throws SQLException {
        /* 加载sql语句 */
        this.pstatement = loadObject(sql, args);
        /* 执行, 并暂存执行是否成功 */
        boolean isSuccess = pstatement.executeUpdate() > 0;
        /* 关闭 */
        pstatement.close();
        /* 返回执行是否成功 */
        return isSuccess;
    } 

    /* 执行查询语句 */
    protected ResultSet executeQuery(String sql, Object... args) throws SQLException {
        /* 加载sql语句 */
        this.pstatement = loadObject(sql, args);
        /* 执行查询 */
        ResultSet resultSet = pstatement.executeQuery();
        /* 返回结果， 因为pstatement关闭后将无法获取结果， 所以不关闭 */
        return resultSet;
    }

    /* 加载sql语句参数 */
    protected PreparedStatement loadObject(String sql, Object... args) throws SQLException {
        /* 将语句和参数加载到PreparedStatement对象中 */
        this.pstatement = connection.prepareStatement(sql);
        /* 遍历参数表 */
        for (int i = 0; i < args.length; i++) {
            /* 设置参数 */
            pstatement.setObject(i + 1, args[i]);
        }
        /* 返回PreparedStatement对象 */
        return pstatement;
    }

    /* 关闭数据库连接 */
    public void close() throws SQLException {
        closePreparedStatement();
        this.connection.close();
    }

    /* 关闭PreparedStatement */
    public void closePreparedStatement() throws SQLException {
        this.pstatement.close();
    }

}
